package com.zimin.common.utils;

import org.springframework.core.NamedThreadLocal;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.util.Objects;

/**
 *
 * Used to bind the current request and context and provide a way to get the current request
 *
 * @author zimin
 */
public class ServerRequestContextHolder {
    private static final ThreadLocal<ServerHttpRequest> REQUESTS = new NamedThreadLocal<>("Thread ServerHttpRequest");

    /**
     * Store {@link ServerHttpRequest} to {@link ThreadLocal} in the current thread
     *
     * @param request {@link ServerHttpRequest}
     */
    public static void put(ServerHttpRequest request){

        //When the request time out, the reset will be invalid
        //because the timeout thread is the thread of hystrix, not the thread of HTTP
        if(Objects.nonNull(get())) {
            reset();
        }

        if(request != null){
            REQUESTS.set(request);
        }
    }

    /**
     * Get the current thread {@link ServerHttpRequest} from {@link ThreadLocal}
     *
     * @return {@link ServerHttpRequest}
     */
    public static ServerHttpRequest get(){
        ServerHttpRequest request = REQUESTS.get();
        return request;
    }

    /**
     * Clear the current thread {@link ServerHttpRequest} from {@link ThreadLocal}
     */
    public static void reset(){
        REQUESTS.remove();
    }
}